package com.codeest.geeknews.util.okhttp;

import android.content.Context;

import com.codeest.geeknews.app.App;
import com.codeest.geeknews.util.notify.DownloadNotifyManager;
import com.codeest.geeknews.util.notify.NotifyId;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 陈丰尧 on 2017/2/2.
 */
public class DownloadManager {
    private static final AtomicReference<DownloadManager> INSTANCE = new AtomicReference<>();
    private HashMap<String, Call> downCalls;//用来存放各个下载的请求
    private LinkedHashMap<String, DownloadInfo> downloads;//用来存放各个下载的请求
    private OkHttpClient mClient;//OKHttpClient;
    //private NotificationUtil mNotificationUtil;

    private DownloadNotifyManager downloadNotifyManager;

    //获得一个单例类
    public static DownloadManager getInstance() {
        for (; ; ) {
            DownloadManager current = INSTANCE.get();
            if (current != null) {
                return current;
            }
            current = new DownloadManager();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }

    private DownloadManager() {
        downCalls = new HashMap<>();
        downloads = new LinkedHashMap<>();
        mClient = new OkHttpClient.Builder().build();
    }

    /**
     * 开始下载
     *
     * @param url              下载请求的网址
     * @param downLoadObserver 用来回调的接口
     */
    public void download(String url, final Observer downLoadObserver) {
        download(App.getInstance(), url, downLoadObserver);
    }

    /**
     * 开始下载(带发送广播的时候用这个方法)
     *
     * @param url              下载请求的网址
     * @param downLoadObserver 用来回调的接口
     */
    public void download(Context context, String url, final Observer downLoadObserver) {
        Observable.just(url)
                .filter(new Predicate<String>() {//filter 是用于过滤数据的，返回false表示拦截此数据。
                    @Override
                    public boolean test(@NonNull String s) throws Exception {
                        return !downCalls.containsKey(s);//call的map已经有了,就证明正在下载,则这次不下载
                    }
                })
                .flatMap(new Function<String, ObservableSource<DownloadInfo>>() {
                    @Override
                    public ObservableSource<DownloadInfo> apply(@NonNull String s) throws Exception {
                        return Observable.just(createDownInfo(s));
                    }
                })
                .map(new Function<DownloadInfo, DownloadInfo>() {
                    @Override
                    public DownloadInfo apply(@NonNull DownloadInfo o) throws Exception {
                        return getRealFileName(o);//检测本地文件夹,生成新的文件名
                    }
                })
                .flatMap(new Function<DownloadInfo, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(@NonNull DownloadInfo downloadInfo) throws Exception {
                        return Observable.create(new DownloadSubscribe(downloadInfo));
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//在主线程回调
                .subscribeOn(Schedulers.io())//在子线程执行
                .subscribe(downLoadObserver);//添加观察者
        downloadNotifyManager = new DownloadNotifyManager(context);//TODO ........注意这里
    }

    /**
     * 把OKhttp取消下载任务（并把已下载置为初始即断点续传从0开始）同时移除通知视为取消下载
     * 取消下载时写入数据会抛出 java.net.SocketException: recvfrom failed: EBADF (Bad file number)
     *
     * @param url-
     */
    public void cancel(String url) {
        stop(url);
        downloadNotifyManager.remove(NotifyId.ID_DOWOLOAD);
    }

    /**
     * 把OKhttp取消下载任务（断点续传从已下载长度开始）同时不移除通知视为暂停下载
     * 暂停下载时写入数据会抛出 java.net.SocketException: recvfrom failed: EBADF (Bad file number)
     *
     * @param url-
     */
    public void stop(String url) {
        Call call = downCalls.get(url);
        if (call != null) {
            call.cancel();//取消
        }
        downCalls.remove(url);
        downloads.remove(url);
    }

    /**
     * 创建DownInfo
     *
     * @param url 请求网址
     * @return DownInfo
     */
    private DownloadInfo createDownInfo(String url) {
        DownloadInfo downloadInfo = new DownloadInfo(url);
        long contentLength = getContentLength(url);//获得文件大小
        downloadInfo.setTotal(contentLength);
        String fileName = url.substring(url.lastIndexOf("/"));
        //String fileName = getFileName(url);
        downloadInfo.setFileName(fileName);
        downloads.put(url, downloadInfo);
        return downloadInfo;
    }

    /**
     * 先找到已下载过的文件长度，实现断点续传
     *
     * @param downloadInfo-
     * @return --
     */
    private DownloadInfo getRealFileName(DownloadInfo downloadInfo) {
        String fileName = downloadInfo.getFileName();
        long downloadLength = 0, contentLength = downloadInfo.getTotal();
        File file = new File(App.getInstance().getExternalCacheDir(), fileName);
        if (file.exists()) {
            //找到了文件,代表已经下载过,则获取其长度
            downloadLength = file.length();
        }
        //之前下载过,需要重新来一个文件
        int i = 1;
        while (downloadLength >= contentLength) {
            int dotIndex = fileName.lastIndexOf(".");
            String fileNameOther;
            if (dotIndex == -1) {
                fileNameOther = fileName + "(" + i + ")";
            } else {
                fileNameOther = fileName.substring(0, dotIndex)
                        + "(" + i + ")" + fileName.substring(dotIndex);
            }
            File newFile = new File(App.getInstance().getExternalCacheDir(), fileNameOther);
            file = newFile;
            downloadLength = newFile.length();
            i++;
        }
        //设置改变过的文件名/大小
        downloadInfo.setProgress(downloadLength);
        downloadInfo.setFileName(file.getName());
        downloadInfo.setFilePath(file.getAbsolutePath());
        return downloadInfo;
    }

    /**
     * 从url响应中获取文件名(头部filename):
     * int location = result.indexOf("filename");
     * if (location >= 0) {
     * result = result.substring(location + "filename".length());
     * filename = result.substring(result.indexOf("=") + 1);
     * isok = true;
     * }
     * <p>
     * 如果没有改头部则从路径中获取:
     * if (filename == null || "".equals(filename)) {
     * filename = url.substring(url.lastIndexOf("/") + 1);
     * }
     * <p>
     * Allow →GET DELETE HEAD PUT POST OPTIONS
     * Connection →keep-alive
     * Content-Length →337
     * Content-Type →application/vnd.android.package-archive
     * Date →Thu, 20 Jul 2017 06:15:31 GMT
     * EagleId →0e77724815005313311245639e
     * Server →Tengine
     * Timing-Allow-Origin →*
     * Via →cache14.l2em21[49,405-0,M], cache20.l2em21[50,0], cache6.cn588[153,405-0,M], cache8.cn588[154,0]
     * X-Cache →MISS TCP_MISS dirn:-2:-2
     * X-Swift-CacheTime →1
     * X-Swift-SaveTime →Thu, 20 Jul 2017 06:15:31 GMT
     * x-oss-request-id →59704A8323A8DAFFCF6CF5B9
     *
     * @param url 下载地址
     * @return
     */
    private String getFileName(String url) {
        String filename = "";
        boolean isok = false;
        // 从UrlConnection中获取文件名称
        try {
            URL myURL = new URL(url);
            URLConnection conn = myURL.openConnection();
            if (conn == null) {
                return null;
            }
            Map<String, List<String>> hf = conn.getHeaderFields();
            if (hf == null) {
                return null;
            }
            Set<String> key = hf.keySet();
            if (key == null) {
                return null;
            }

            for (String skey : key) {
                List<String> values = hf.get(skey);
                for (String value : values) {
                    String result;
                    try {
                        result = new String(value.getBytes("ISO-8859-1"), "GBK");
                        int location = result.indexOf("filename");
                        if (location >= 0) {
                            result = result.substring(location + "filename".length());
                            filename = result.substring(result.indexOf("=") + 1);
                            isok = true;
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }// ISO-8859-1 UTF-8 gb2312
                }
                if (isok) {
                    break;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 从路径中获取
        if (filename == null || "".equals(filename)) {
            filename = url.substring(url.lastIndexOf("/") + 1);
        }
        //类似这种变态服务器下载路径http://ucdl.25pp.com/fs08/2017/04/21/9/110_592fe46f07a691e40bc1530e94c13371.apk
        // ?sf=4221697&vh=c143331f3003ad917f5b3abe7cebbd0f&sh=10&cc=1398333781&appid=7047937&packageid=200482321
        // &md5=b9ba1993bc850276694d451b278395a8&apprd=7047937&pkg=com.geektoy.nfcemulator&vcode=408
        // &fname=NFC+Emulator&pos=detail-ndownload-com.geektoy.nfcemulator无filename
        // 截取后的文件名很长创建File会失败
        return filename;
    }

    public LinkedHashMap<String, DownloadInfo> getDownloads() {
        return downloads;
    }

    private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> {
        private DownloadInfo downloadInfo;

        public DownloadSubscribe(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
        }

        @Override
        public void subscribe(ObservableEmitter<DownloadInfo> e) /*throws Exception */ {
            //mNotificationUtil.showNotification(100);
            downloadNotifyManager.showNotification(NotifyId.ID_DOWOLOAD, downloadInfo);
            String url = downloadInfo.getUrl();
            long downloadLength = downloadInfo.getProgress();//已经下载好的长度
            long contentLength = downloadInfo.getTotal();//文件的总长度
            //初始进度信息
            e.onNext(downloadInfo);

            Request request = new Request.Builder()
                    //确定下载的范围,添加此头,则服务器就可以跳过已经下载好的部分
                    .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength)
                    .url(url)
                    .build();
            Call call = mClient.newCall(request);
            downCalls.put(url, call);//把这个添加到call里,方便取消
            Response response = null;
            InputStream is = null;
            FileOutputStream fileOutputStream = null;
            try {
                response = call.execute();
                File file = new File(App.getInstance().getExternalCacheDir(), downloadInfo.getFileName());
                try {
                    is = response.body().byteStream();
                    fileOutputStream = new FileOutputStream(file, true);
                    byte[] buffer = new byte[2048];//缓冲数组2kB
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        downloadLength += len;
                        downloadInfo.setProgress(downloadLength);
                        e.onNext(downloadInfo);
                        //
                        int progress = (int) (downloadInfo.getProgress() * 100 / downloadInfo.getTotal());
                        downloadNotifyManager.updateProgress(NotifyId.ID_DOWOLOAD, progress);
                    }
                    fileOutputStream.flush();
                    downCalls.remove(url);
                    downloads.remove(url);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            } finally {
                //关闭IO流
                assert is != null;
                try {
                    is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                assert fileOutputStream != null;
                try {
                    fileOutputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                //IOUtil.closeAll(is, fileOutputStream);
            }
            e.onComplete();//完成
            downloadNotifyManager.remove(NotifyId.ID_DOWOLOAD);
        }
    }

    /**
     * 获取下载长度
     *
     * @param downloadUrl
     * @return
     */
    private long getContentLength(String downloadUrl) {
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response != null && response.isSuccessful()) {
                long contentLength = response.body().contentLength();
                response.close();
                return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DownloadInfo.TOTAL_ERROR;
    }
}